package tr.richfacesext.components.rating;

import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;

import tr.richfacesext.components.ComponentUtils;

/**
 * 
 * @author mert
 *
 */
public class Rating extends UIInput {

	private Boolean _fixedValue;
	
	private String _onSuccessJSCall;
	

	public boolean isFixedValue() {
		if(_fixedValue != null )
			return _fixedValue.booleanValue();

		ValueBinding vb = getValueBinding("fixedValue");
		return vb != null ? ComponentUtils.getBooleanValue(getFacesContext(),vb) : false;
	}

	public void setFixedValue(boolean value) {
		_fixedValue = value;
	}
	
	public String getOnSuccessJSCall() {
		if(_onSuccessJSCall != null )
			return _onSuccessJSCall;
		
		ValueBinding vb = getValueBinding("onSuccessJSCall");
		return vb != null ? (java.lang.String) vb.getValue(getFacesContext()) : null;
	}
	
	public void setOnSuccessJSCall(String value) {
		_onSuccessJSCall = value;
	}

	public Rating() {
		setRendererType(RatingConstants.DEFAULT_RENDERER);
	}

	public String getFamily() {
		return RatingConstants.COMPONENT_FAMILY;
	}

	public Object saveState(FacesContext context) {
		Object values[] = new Object[3];
		values[0] = super.saveState(context);
		values[1] = _fixedValue;
		values[2] = _onSuccessJSCall;
		
		return ((Object) values);
	}
	
	public void restoreState(FacesContext context, Object state) {
		Object values[] = (Object[]) state;
		
		super.restoreState(context, values[0]);
		_fixedValue = (Boolean) values[1];
		_onSuccessJSCall = (String) values[2];
	}

	public Float getRatingValue() {
		if (getValue() == null)
			return null;
		
		if (getValue() instanceof Float)
			return (Float) getValue();
		
		if(getValue() instanceof Double) {
			Double d = (Double) getValue();
			return new Float(d);
		}
		
		throw new IllegalArgumentException("value property of component should be an instanceof " + Float.class.getName() + " or " + Double.class.getName());		
	}
}